﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GPRSLib;
using System.IO.Ports;
using System.Threading;
using GPRSForm.Database;
using GPRSForm.SMS;
using System.Diagnostics;
namespace GPRSForm.Send_Interface
{
    public partial class AutoSend : UserControl
    {
       
        DataTable dataSend = null;
        DataBase database = null;
        Thread autoSendThread = null;
        gmsClass gms = null;
        SerialPort port = null;
        public AutoSend()
        {
            InitializeComponent();
            initComponent();
            this.Name = "autosend";
           
        }
        void initComponent()
        {
            dataGridView_sent.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
        }
        public delegate void logDelegate(string id,string phone,string content,string date);

        public void logMessage(string id,string phone,string content,string date)
        {
            if (InvokeRequired)
            {
                this.Invoke(new logDelegate(logMessage), id,phone,content,date);
            }
            else
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(dataGridView_sent);
                row.Cells[0].Value = id;
                row.Cells[1].Value = phone;
                row.Cells[2].Value = content;
                row.Cells[3].Value = date;
                dataGridView_sent.Rows.Add(row);
            }
        }
        /*
        * method send SMS
        */
        public bool sendSMS(string phoneNumber, string smg)
        {
            // send message with phone and message
            return gms.sendMsg(port, phoneNumber, smg);
           
        }
        private void autoSend()
        {
            bool result = true;
            double date;
            string phone = "";
            string text = "";
            string nDateStr = "";
            string id;
            DateTime dt;
            while (true)
            {
                dataSend = database.getSMS();
                for (int i = 0; i < dataSend.Rows.Count; i++)
                {

                    id = dataSend.Rows[i]["sms_id"].ToString();
                    phone = dataSend.Rows[i]["telephone_no"].ToString();
                    text = dataSend.Rows[i]["content"].ToString();
                    date = GPRSForm.SMS.CommonFunction.ConvertToUnixTimestamp(DateTime.Now);

                    result = sendSMS(phone, text);
                    EventLog.WriteEntry("SMS", "send sucesss");
                    if (result)
                    {
                        if (!database.updateSMS(id, date))
                        {
                            MessageBox.Show("dataBase not update.Please try again", "DataBase", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        /*while (!database.updateSMS(id, date))
                        {
                            MessageBox.Show("dataBase not update.Please try again", "DataBase", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }*/

                        EventLog.WriteEntry("SMS", "update sucesss");
                        // update on Form
                        dt = CommonFunction.ConvertFromUnixTimestamp(date);
                        //format date time
                        nDateStr = String.Format("{0:u}", dt);
                        logMessage(id, phone, text, nDateStr);
                        result = false;
                    }
                    //Thread.Sleep(1000);
                }
                Thread.Sleep(2000);
            }
        }
        private void btAutoSend_Click(object sender, EventArgs e)
        {
            if (autoSendThread != null)
            {
                if (!autoSendThread.IsAlive)
                {
                    autoSendThread = new Thread(new ThreadStart(autoSend));
                    autoSendThread.Start();
                }
                
            }
            else
            {
                autoSendThread = new Thread(new ThreadStart(autoSend));
                autoSendThread.Start();
            }
            this.btAutoSend.Enabled = false;
            this.btStopAutosend.Enabled = true;
        }

        private void btStopAutosend_Click(object sender, EventArgs e)
        {
            
            this.btAutoSend.Enabled = true;
            this.btStopAutosend.Enabled = false;
            this.autoSendThread.Abort();
        }

        private void SwitchNormalSend_Click(object sender, EventArgs e)
        {
            if (autoSendThread == null)
            {
                changeToNormalMode();
            }
            else
            {
                if (autoSendThread.IsAlive && !btAutoSend.Enabled)
                {
                    // thread Start
                    MessageBox.Show("Auto sening is running .Please stop it", "Auto Sending",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
                else
                {
                    changeToNormalMode();
                }
            }
           
        }

        private void AutoSend_EnabledChanged(object sender, EventArgs e)
        {
            if (this.Enabled)
            {
                port = GPRSForm.GlobalClass.portVar;
                database = GPRSForm.GlobalClass.dataBaseVar;
                gms = GPRSForm.GlobalClass.gmsVar;
            }
        }
        private void changeToNormalMode()
        {
            Control[] list = this.Parent.Controls.Find("normalsend", true);
            if (list != null)
            {
                NormalSend nSend = (NormalSend)list[0];
                this.Visible = false;
                this.Enabled = false;
                nSend.Enabled = true;
                nSend.Visible = true;
            }
            else
            {
                MessageBox.Show("Not found Normal mode", "Auto Sending", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
        }
    }
}
